﻿
var arrColor = new Array("#C5DBEC");
var arrColor1=new Array("#F5A9A9","#F5B521","#81F7D8","#A9A9F5","#AEB404","#BEF781","#BE81F7","#F781F3","#BEF781","#0174DF","#2EFEF7");
var strDims;

function fillRelatioDiv() {

    var list_id = $("#drp_mst").val();
    var Ids = jQuery("#dataGrid").getGridParam('selarrrow');

    //select graph tab
    $("#tabsRel").tabs("select", 0);
    $("#relError").text('');

    //list_id = 9;
    arrColor = new Array("#C5DBEC");

    $.ajax({
        async: false,
        type: 'POST',
        url: "MasterCallback.aspx?operation=GetRelDataGraph&Mlist_id=" + list_id + "&Ids=" + Ids,
        data: "",
        success: function (str1) {
            //debugger;
            var arr = str1.split('^');

            if (arr[0] == "0") {
                $("#relMstError").show();
                $("#relMstError").fadeOut(8000);
                return false;
            }
            else {

                $("#tabsRel").show();
                var res = arr[1];
                var str = eval('(' + res + ')')
                if (str.length > 0) {
                    if ($("#container_0").attr("list_id") == undefined) {
                        $("#container_0").attr("list_id", list_id);
                        var strDivList = "<div style=\"margin-left: 20px; font-weight: bold;color:#2E6E9E;\">" + $("#drp_mst option:selected").text() + "</div>";
                        $("#container_0").append(strDivList);
                    }
                }
                // $("#tmplGraph").tmpl(str).appendTo("#container_0");
                //<div style="margin-left: 20px; font-weight: bold;">Department </div>
                //debugger;

                for (i = 0, len = str.length; i < len; i++) {
                    //debugger;
                    if ($('div[id="g' + str[i].rel_col + '"]').length == 0) {
                        //                var strDiv = "<div id='" + str[i].rel_col + "' dim_id='" + str[i].rel_col + "' class='div' style='background-color:" + arrColor[0] + ";' onclick='divClick(\"" + str[i].rel_col + "\");' ParentId='null'  colorIndex='-1'>" + str[i].show_col + "</div>";
                        var strDiv = "<div id='g" + str[i].rel_col + "' class='div' style='background-color:" + arrColor[0] + ";' onclick='divClick(\"" + str[i].rel_col + "\");' ParentId='null'  colorIndex='-1'>" + str[i].show_col + "</div>";
                        $("#container_0").append(strDiv);
                        $('#' + str[i].rel_col).bind("dblclick", divClick);
                        //bind context menu
                        ContextMenuBind("g" + str[i].rel_col);
                    }
                }
            }

            //repaint verything
            jsPlumb.repaintEverything();

        },
        error: function (x, e) {
            //debugger;
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

function menuClick(action) {

    //debugger;
    var target = action.target.id;

    if (target == "aRemove") {
        //debugger;
       var parIdArr=new Array();
       if ($('div[id="' + $("#del-menu").attr("clickid") + '"]').attr("parentId") != "null" && $('div[id="' + $("#del-menu").attr("clickid") + '"]').attr("parentId") != undefined)
       {
           parIdArr = $('div[id="' + $("#del-menu").attr("clickid") + '"]').attr("parentId").split(':');
       }     

     //   if ($("#" + parId).length != 0) {
     if (parIdArr.length != 0) {
            /////http://code.google.com/p/jsplumb/issues/detail?id=34

            for (i = 0; i < parIdArr.length; i++) {
                //debugger;
                var connectionsDict =
                                jsPlumb.getConnections({ source: parIdArr[i], target: $("#del-menu").attr("clickid") });

                $(connectionsDict[0].endpoints).each(function (index) {
                    if ($(this)[0].elementId == parIdArr[i]) {
                        jsPlumb.removeEndpoint(parIdArr[i], connectionsDict[0].endpoints[index]);
                    }
                });
            }          
        }

        GetChildObjects($("#del-menu").attr("clickid"));
        jsPlumb.repaintEverything();

    }
    else if (target == "aQuit") {
        $("#del-menu").hide();
    }
    else {
            
         //show ul on detail click
        if ($('#tabsRel').tabs('length') == 1) {
            $("#ulRel").show();
        }   
                   
        var list_id = $('div[id="' + $("#del-menu").attr("clickid") + '"]').parent().attr("list_id")
        var id = $("#del-menu").attr("clickid");
        var parId = $('div[id="' + $("#del-menu").attr("clickid") + '"]').attr("parentId");
        var node_val = $('div[id="' + $("#del-menu").attr("clickid") + '"]').text();
        if (parId == "null") {parId = "";}

        id = id.substring(1, id.length);

        if ($('table[id^="' + id + '-"]', "#tabsRel").length > 0) {
            //debugger;
            var arr = $('table[id^="' + id + '-"]', "#tabsRel").attr("id").split('-');
            //select that tab
            $("#tabsRel").tabs("select", arr[1])

        }
        else {
            getRelData(parId, list_id, id, node_val);
        }
    }
}

function Connect(parent, child, contid,colorIndex) {

   
    var exampleDropOptionsP = {
        tolerance: 'touch',
        hoverClass: 'dropHover',
        activeClass: 'dragActive'
    };

    var  colorP = arrColor1[colorIndex];
    var exampleEndpointP = {
        paintStyle: { fillStyle: colorP },
        isSource: true,
        connectorStyle: { strokeStyle: colorP, lineWidth: 1 },
        connector: ["Straight", { curviness: 13}],
        endpoint: ["Dot", { radius: 2.5, hoverClass: "myEndpointHover"}],
        maxConnections: -1,
        isTarget: true,
        dropOptions: exampleDropOptionsP//,
    };

    var colorPR = "#FFFFFF"; 
    var exampleEndpointPR = {
        paintStyle: { fillStyle: colorP },
        isSource: true,
        connectorStyle: { strokeStyle: colorP, lineWidth: 1 },
        connector: ["Straight", { curviness: 13}],
        endpoint: ["Dot", { radius: .1, hoverClass: "myEndpointHover"}],
        maxConnections: -1,
        isTarget: true,
        dropOptions: exampleDropOptionsP//,
    };

    var options1 = {
        stop: function (e, ui) {
            if (revTest === true) {
                jsPlumb.repaint(this.id);
            }
        }
    };

   // debugger;
    child = "" + child + "";
  
    var e5 = jsPlumb.addEndpoint("g"+ parent, { anchor: ["RightMiddle"] }, exampleEndpointPR);
    var e6 = jsPlumb.addEndpoint("g" + child, { anchor: ["LeftMiddle"] }, exampleEndpointP); 

    var overlaysP = [
                ["Arrow", { length: 12 }, { location: 0.99}]   //, { foldback: 1.0 }
            ];

    //debugger;
    jsPlumb.connect({ source: e5, target: e6, overlays: overlaysP }); 
    jsPlumb.repaintEverything();

}

function divClick(parentid) {

    //debugger;
    var list_id = $("#g" + parentid, "#rel-frame").parent().attr("list_id");
    var parId = $("#g" + parentid, "#rel-frame").parent().attr("id").split('_');
    var contid = Number(parId[1]) + 1;

    //if ($("#container_" + contid).find($('div[parentid="' + parentid + '"]')).length == 0) {
    if ($("#container_" + contid).length == 0) {
        //add parent div
        var strDiv = '<div id="container_' + contid + '" style="float: left;"></div>';
        $("#rel-frame").append(strDiv);     
    }

    $.ajax({
        async: false,
        type: 'GET',
        url: "MasterCallback.aspx?operation=GetRelDataChildGraph&Mlist_id=" + list_id + "&parentid=" + parentid,
        data: "",
        success: function (result) {
            //debugger;
            $("#relError").text("");

            var arr = result.split('^');
            var res = arr[1];
            var str = eval('(' + res + ')');

            //set the list_id to container
            if (str.length != 0) {
                if ($("#container_" + contid).attr("list_id") == undefined) {
                    $("#container_" + contid).attr("list_id", arr[0]);
                    var strDivList = "<div style=\"margin-left: 20px; font-weight: bold;color:#2E6E9E;\">" + $("#drp_mst option[value='" + arr[0] + "']").text() + "</div>";
                    $("#container_" + contid).append(strDivList);
                }
            }

            if (str.length != 0) {
                //debugger;
                var index;
                var bClicked = false;

                if ($("#container_" + contid).attr("index") == undefined) {
                    index = 0;
                }
                else {
                    index = $("#container_" + contid).attr("index");
                }

                //debugger;
                //find if already clicked
                var colorIndex = $('div[id="g' + parentid + '"]').attr("colorIndex");

                if ($("#container_" + contid).find($('div[parentid="' + parentid + '"]')).length != str.length) {

                    for (i = 0, len = str.length; i < len; i++) {

                        //if that id with same parent_id doesn't exist in that container
                        //  then append that div
                        if ($('div[id="g' + str[i].id + '"]', "#container_" + contid).length == 0) {

                            var strDiv = "<div parentid='g" + str[i].parentId + "' id='g" + str[i].id + "' class='div' style='background-color:" + arrColor[contid] + ";' onclick='divClick(\"" + str[i].id + "\");'  colorIndex='-1'>" + str[i].value + "</div>";

                            $("#container_" + contid).append(strDiv);
                            $('#' + str[i].rel_col).bind("dblclick", divClick);
                        }
                        else {

                            //debugger;
                            var tempParent = $('div[id="g' + str[i].id + '"]').attr("parentid").split(':');
                            if (tempParent.length > 0) {

                                var ind = jQuery.inArray("g" + String(str[i].parentId), tempParent);

                                if (ind == -1) {
                                    tempParent = tempParent + ":g" + str[i].parentId;
                                    $('div[id="g' + str[i].id + '"]').attr("parentid", tempParent);
                                }
                            }
                        }

                        //for arrow
                        if (colorIndex == -1) {
                            Connect(parentid, str[i].id, contid, index);
                        }
                        else {
                            Connect(parentid, str[i].id, contid, colorIndex);
                        }

                        ContextMenuBind("g" + str[i].id);
                    }
                }

                if (colorIndex == -1) {
                    $('div[id="g' + parentid + '"]').attr("colorIndex", index);
                    if (index == 10) {
                        index = 0;
                    }

                    index = parseInt(index) + 1;
                    $("#container_" + contid).attr("index", index);
                }
            }
            else {

                $("#relError").text("No related record is there ! ");
                return false;
            }

            window.location.hash = $('div[parentid="' + parentid + '"]').attr("id");

        },
        error: function (x, e) {
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });  
}

function ContextMenuBind(Id) {

   // debugger;
    $("#" + Id, "#rel-frame").bind("contextmenu", function (e) {
      //  debugger;
//        $('#del-menu').css({
//            //top: e.pageY - 179 + 'px', ask naval
//           // top: e.pageY - ($('#tabsRel-0').offset().top + 12) + 'px',  //($("#" + Id)[0].offsetTop + 10) + 'px',   //$('#tabsRel-0').scrollTop()
//            top: ((e.pageY - $('#tabsRel-0').offset().top +12) + $('#tabsRel-0').scrollTop())-24 + 'px',
//            left: ((e.pageX - $('#tabsRel-0').offset().left + 12) + $('#tabsRel-0').scrollLeft())-24 + 'px'  //e.pageX-50 + 'px'
//            //left: e.pageX - ($('#tabsRel-0').offset().left + 12 + $('#tabsRel-0').scrollLeft()) + 'px'  //e.pageX-50 + 'px'
//        }).show();

//        ////original
        $('#del-menu').css({
            top: e.pageY + 'px', //ask naval          
            left: e.pageX+ 'px'
        }).show();  

        $('#del-menu').attr("clickid", Id);  
        return false;
    });
}



function delHierData(divId) {

    $('div[parentid="' + divId + '"]').each(function (index) {
        //debugger;
        var id = $(this).attr("id");
        $('div[id="' + divId + '"]').remove();

        if ($('div[parentid="' + id + '"]').length == 0) {
            $('div[id="' + id + '"]').remove();
        }
        else {
            GetChildObjects(id);
        }
    });
}

//original
//function GetChildObjects(divId) {

//    debugger;

//    jsPlumb.removeAllEndpoints(divId);
//    jsPlumb.select({ source: divId }).removeAllOverlays();
//    $('div[id="' + divId + '"]').remove();

//    $('div[parentid="' + divId + '"]').each(function (index) {       
//        debugger;
//        var id = $(this).attr("id");
//        if ($('div[parentid="' + id + '"]').length == 0) {
//            jsPlumb.removeAllEndpoints(id);
//            jsPlumb.select({ source: id }).removeAllOverlays();
//            $('div[id="' + id + '"]').remove();
//        }
//        else {
//            GetChildObjects(id);
//        }
//    });
//}


function GetChildObjects(divId) {

    //debugger;
    jsPlumb.removeAllEndpoints(divId);
    jsPlumb.select({ source: divId }).removeAllOverlays();
    $('div[id="' + divId + '"]').remove();

    $('div[parentid="' + divId + '"],[parentid^="' + divId + ':"],[parentid$=":' + divId + '"],[parentid*=":' + divId + ':"]').each(function (index) {
        //debugger;
        var id = $(this).attr("id");

        if ($(this).attr("parentid") == divId) {
            if ($('div[parentid="' + id + '"]').length == 0) {
                jsPlumb.removeAllEndpoints(id);
                jsPlumb.select({ source: id }).removeAllOverlays();
                $('div[id="' + id + '"]').remove();
            }
            else {
                GetChildObjects(id);
            }
        }
        else {
            //debugger;
            var parIdArr = new Array();
            parIdArr = $(this).attr("parentid").split(':');

            var index = jQuery.inArray(divId, parIdArr);
            parIdArr.splice(index, 1);
            var strParIds = parIdArr.join(':'); 
            $(this).attr("parentid",strParIds);
        }
    });
}


//add report tab dynamically
function addRelTab(parId, list_id, id, node_val, strDims) {
    
    //debugger;
    var len = $('#tabsRel').tabs('length');
    $("#tabsRel").tabs("add", "#tabsRel-" + (len), node_val);
    var list_name = $("#drp_mst option[value='" + list_id + "']").text();

    var arr = [len];
    var obj = [
      {
          index: len,
          node_val: node_val,       
          list_id: list_id,
          id: id,
          list_name: list_name,
          strDims: strDims
      }
      ];
 
    $("#tmplDynRel").tmpl(obj).appendTo("#tabsRel-" + (len));

    //select new tab
    $("#tabsRel").tabs("select", len);
    //css of dimension tab (to make a class and apply)
    $("#tabsRel-" + (len)).css("align", "center");
    $("#tabsRel-" + (len)).addClass("tabsRel");   
}

function getRelData(parId, list_id, id, node_val) {

    //debugger;
    $.ajax({
        async: true,
        type: 'GET',
        url: "MasterCallback.aspx?operation=GetRelDataDetail&list_id=" + list_id + "&id=" + id + "&parent_id=" + parId,
        data: "",
        dataType: "json",
        success: function (data) {
            //debugger;
            //alert('p');
            strDims = $('div[id="g' + id + '"]').text();
            var strContent = GetParentDims("g" + id, strDims);

            addRelTab(parId, list_id, id, node_val, strDims);
            var len = $('#tabsRel').tabs('length');

            //without source original
            //$("#tmplTableTr").tmpl(data).appendTo("#" + id + "-" + (len - 1));
            //with source new
            $("#tmpldim").tmpl(data).appendTo("#" + id + "-" + (len - 1));
        },
        error: function (x, e) {
            alert(x.readyState + " " + x.status + " " + e.msg);
        }
    });
}

////new one
//function ShowRelationDiv() {

//    var list_id = 9; //hardcoded list_id
//    arrColor = new Array("#C5DBEC");

//    $.ajax({
//        async: false,
//        type: 'POST',
//        url: "MasterCallback.aspx?operation=GetRelDataGraph&Mlist_id=" + list_id,
//        data: "",
//        // dataType: "json",
//        success: function (str1) {
//            //debugger;
//            var arr = str1.split('^');
//            var res = arr[1];
//            var str = eval('(' + res + ')')

//            $("#container_0").empty();
//            $("#container_0").attr("list_id", list_id);
//            // $("#tmplGraph").tmpl(str).appendTo("#container_0");

//            for (i = 0, len = str.length; i < len; i++) {
//                //debugger;
//                var strDiv = "<div id='g" + str[i].rel_col + "' dim_id='" + str[i].rel_col + "' class='div' style='background-color:" + arrColor[0] + ";' onclick='divClick(\"" + str[i].rel_col + "\");' ParentId='null'  colorIndex='-1'>" + str[i].show_col + "</div>";
//                $("#container_0").append(strDiv);
//                $('#' + str[i].rel_col).bind("dblclick", divClick);
//                //bind context menu
//                ContextMenuBind("g" + str[i].rel_col);
//            }
//        },
//        error: function (x, e) {
//            //debugger;
//            alert(x.readyState + " " + x.status + " " + e.msg);
//        }
//    });
//}

function ClearGraphTab() {

    //debugger;
    //Removes all endpoints and connections 
    // and clears the listener list
    jsPlumb.reset();

    //hide ul until detail click
    $("#ulRel").hide();

    //clear all container data
    $('div[id^="container_"]').empty();
    $('div[id^="container_"]').removeAttr("list_id");
    $('div[id^="container_"]').removeAttr("index"); //index

    var len = $('#tabsRel').tabs('length');
    $("#tabsRel").hide();

    //remove all rel tabs except 
    //1st one
    if (len > 1) {
        for (i = (len-1); i > 0; i--) {
            $('#tabsRel').tabs('remove', i); 
        }
    }
}

function GetParentDims(id, strContent) {
    //debugger;

    var parid = $('div[id="' + id + '"]').attr("parentid");   

    if (parid != "null" && parid != undefined) {
        strContent = $('div[id="' + parid + '"]').text() + " --> " + strContent;
        GetParentDims(parid,strContent);
    }
    else {
        strDims = strContent;
        return strContent;
    }
}

